import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DialogService } from 'primeng/primeng';
import { MdlDialogService, MdlSnackbarService } from '@angular-mdl/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { ConfirmationService } from 'primeng/api';
import { TransitComponent } from './transit/transit.component';
import { RollbackComponent } from './rollback/rollback.component';
import { FinishComponent } from './finish/finish.component';
import { CancelComponent } from './cancel/cancel.component';

@Injectable()
export class CommandDispatcherService {
    constructor(
        private http: HttpClient,
        private router: Router,
        private mdlSnakbarService: MdlSnackbarService,
        private mdlDialogService: MdlDialogService,
        private confirmationService: ConfirmationService,
        public dialogService: DialogService) {
    }

    dispatcher(command: any, selectedData: any, obj: any, callback: any) {
        switch (command.requestType) {
            case 1:
                //Ajax请求
                if (command.needConfirm) {
                    this.confirmationService.confirm({
                        message: '您确定要对选中案卷执行' + command.menuName + '操作吗?',
                        accept: () => {
                            this.ajax(command, selectedData, obj, callback);
                        }
                    });
                } else {
                    this.ajax(command, selectedData, obj, callback);
                }
                break;
            case 2:
                //文件下载
                break;
            case 3:
                //打开窗口
                this.dialog(command, selectedData, obj, callback);
                break;
            case 4:
                //路由跳转
                let urlparams = command.requestUrl.split('?');
                let params = {};
                if (urlparams[1]) {
                    urlparams[1].split('&').forEach(e => {
                        let p = e.split('=');
                        params[p[0]] = p[1];
                    });
                }
                //业务号
                if (obj.bizId) {
                    if (urlparams[0].indexOf(':bizId') >= 0) {
                        urlparams[0] = urlparams[0].replace(':bizId', obj.bizId);
                    }
                    params['bizId'] = obj.bizId;
                }
                //分组参数
                if (obj.taskListGroupId) {
                    if (urlparams[0].indexOf(':taskListGroupId') >= 0) {
                        urlparams[0] = urlparams[0].replace(':taskListGroupId', obj.taskListGroupId);
                    }
                    params['taskListGroupId'] = obj.taskListGroupId;
                }
                //列表参数
                if(obj.taskListId){
                    params['taskListId'] = obj.taskListId;
                }
                if (selectedData && selectedData.length > 0 && command['menuActIndepend']) {
                    //需要选中案卷的时候操作
                    let recId = selectedData[0]['rec_id'] || selectedData[0]['recId'];
                    if (!recId) {
                        this.mdlDialogService.alert('开箱语句配置错误，无recid字段');
                        return;
                    }
                    params['recId'] = recId;
                    //流程实例
                    let actId = selectedData[0]['act_id'] || selectedData[0]['actId'] || 0;
                    params['actId'] = actId;
                    //环节定义
                    let actDefId = selectedData[0]['act_def_id'] || selectedData[0]['actDefId'] || 0;
                    params['actDefId'] = actDefId;
                    this.router.navigate([urlparams[0], params]);
                } else {
                    this.router.navigate([urlparams[0], params]);
                }
                break;
            default:
                console.error("CommandDispatcherService Unknow RequestType...")
        }
    }
    /** Ajax响应事件 */
    ajax(command, selectedData, obj, callback) {
        let reqUrl = command.requestUrl;
        if (command.requestParams) {
            reqUrl += '?'
            let params = command.requestParams.split(',');
            let pStr = '';
            params.forEach(p => {
                let nv = p.split(':');
                pStr += nv[1] + '=' + selectedData[0][nv[0]] + '&'
            });
            reqUrl += pStr;
        }
        this.http.get(reqUrl).subscribe(data => {
            callback.apply(obj);
            this.mdlSnakbarService.showToast('操作成功！');
        });
    }

    /**窗口响应事件 */
    dialog(command, selectedData, obj, callback) {
        let requestParams = {};
        try {
            if ("" == command.requestParams) {
                command.requestParams = "{}";
            }
            requestParams = JSON.parse(command.requestParams)
        } catch (error) {
            console.error("CommandDispatcherService Params Error, Must Be a Json String...");
        }
        //高度自适应计算
        if (requestParams['height'] == '100%') {
            requestParams['height'] = $('body').height() - 50 + 'px';
        }
        const ref = this.dialogService.open(this.getComponent(command.requestUrl), {
            header: requestParams['header'] || command['menuName'],
            showHeader: true,
            width: requestParams['width'] || "75%",
            contentStyle: { 'height': requestParams['height'] || "550px", 'padding': '0' },
            data: {
                'systemUrl': obj.systemUrl,
                'selectedRecords': command['menuActIndepend'] ? selectedData : null
            }
        });
        ref.onClose.subscribe(data => {
            if (data) {
                //调用回调函数，刷新面板
                callback.apply(obj);
            }
        });
    }

    /** 获取当command对应的组件 */
    private getComponent(componentName) {
        switch (componentName) {
            case 'TransitComponent':
                return TransitComponent;
            case 'RollbackComponent':
                return RollbackComponent;
            case 'FinishComponent':
                return FinishComponent;
            case 'CancelComponent':
                return CancelComponent;
            default: return null;
        }
    }
}